package com.approval.controller;

import com.approval.dto.*;
import com.approval.security.RequirePermission;
import com.approval.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 角色管理控制器
 */
@RestController
@RequestMapping("/roles")
@CrossOrigin(origins = "*")
@RequirePermission(resource = "role", action = "list")
public class RoleManagementController {
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 创建角色
     */
    @PostMapping
    public ResponseEntity<Result<RoleResponse>> createRole(@Valid @RequestBody RoleCreateRequest request) {
        try {
            RoleResponse role = roleService.createRole(request);
            return ResponseEntity.ok(Result.success(role));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 更新角色
     */
    @PutMapping("/{id}")
    public ResponseEntity<Result<RoleResponse>> updateRole(@PathVariable Long id, @Valid @RequestBody RoleUpdateRequest request) {
        try {
            RoleResponse role = roleService.updateRole(id, request);
            return ResponseEntity.ok(Result.success(role));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Result<Void>> deleteRole(@PathVariable Long id) {
        try {
            roleService.deleteRole(id);
            return ResponseEntity.ok(Result.success());
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 根据ID获取角色
     */
    @GetMapping("/{id}")
    public ResponseEntity<Result<RoleResponse>> getRoleById(@PathVariable Long id) {
        try {
            RoleResponse role = roleService.getRoleById(id);
            return ResponseEntity.ok(Result.success(role));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 分页查询角色
     */
    @GetMapping
    public ResponseEntity<Result<PageResponse<RoleResponse>>> getRoles(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String roleName,
            @RequestParam(required = false) String roleType,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "id") String sortField,
            @RequestParam(defaultValue = "asc") String sortOrder) {
        try {
            PageRequestDto pageRequest = new PageRequestDto();
            pageRequest.setPage(page);
            pageRequest.setSize(size);
            pageRequest.setSortField(sortField);
            pageRequest.setSortOrder(sortOrder);
            
            PageResponse<RoleResponse> roles = roleService.getRoles(pageRequest, roleName, roleType, status);
            return ResponseEntity.ok(Result.success(roles));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 获取所有角色
     */
    @GetMapping("/all")
    public ResponseEntity<Result<List<RoleResponse>>> getAllRoles() {
        try {
            List<RoleResponse> roles = roleService.getAllRoles();
            return ResponseEntity.ok(Result.success(roles));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 获取角色树
     */
    @GetMapping("/tree")
    public ResponseEntity<Result<List<RoleResponse>>> getRoleTree() {
        try {
            List<RoleResponse> roles = roleService.getRoleTree();
            return ResponseEntity.ok(Result.success(roles));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 获取角色权限预览
     */
    @GetMapping("/{id}/permissions")
    public ResponseEntity<Result<RolePermissionPreviewResponse>> getRolePermissionPreview(@PathVariable Long id) {
        try {
            RolePermissionPreviewResponse preview = roleService.getRolePermissionPreview(id);
            return ResponseEntity.ok(Result.success(preview));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 为用户分配角色
     */
    @PostMapping("/assign/user")
    public ResponseEntity<Result<Void>> assignRolesToUser(@Valid @RequestBody UserRoleAssignRequest request) {
        try {
            roleService.assignRolesToUser(request);
            return ResponseEntity.ok(Result.success());
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 为角色分配权限
     */
    @PostMapping("/assign/permission")
    public ResponseEntity<Result<Void>> assignPermissionsToRole(@Valid @RequestBody RolePermissionAssignRequest request) {
        try {
            roleService.assignPermissionsToRole(request);
            return ResponseEntity.ok(Result.success());
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 获取角色的用户列表
     */
    @GetMapping("/{id}/users")
    public ResponseEntity<Result<List<UserResponse>>> getRoleUsers(@PathVariable Long id) {
        try {
            List<UserResponse> users = roleService.getRoleUsers(id);
            return ResponseEntity.ok(Result.success(users));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
}